//
//  HHHPublicClass.m
//  project
//
//  Created by 黄建华 on 2017/9/27.
//  Copyright © 2017年 黄建华. All rights reserved.
//

#import "SNPublicClass.h"
@implementation SNPublicClass

DEF_SINGLETON(SNPublicClass)

- (instancetype)init {
    self = [super init];
    if (self) {
        _selectDate   = [NSDate date];
        _stepArray    = [NSMutableArray array];
        _heartArray   = [NSMutableArray array];
        _oxArray      = [NSMutableArray array];
        _bpMaxArray   = [NSMutableArray array];
        _bpMinArray   = [NSMutableArray array];
        _trackArray   = [NSMutableArray array];
        _checkType    = 1;
        _isCheck      = NO;
        _weatherModel = [WeatherModel getModelFromDB];
        [BackGroundTaskView sharedInstance];
        _selectModel = [SNEveryDayModelHelp getModelFromDBWithDate:_selectDate];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(BecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
        [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(SNPublicClassTimer) userInfo:nil repeats:YES];
        _userModel   = [SNEveryDayModelHelp getUserModel];
        _selectModel = [SNEveryDayModelHelp getModelFromDBWithDate:_selectDate];
        _todaymodel  = [SNEveryDayModelHelp getModelFromDBWithToday];
        _yesModel    = [SNEveryDayModelHelp  getModelFromDBWithYes];
        _lastDateString = [self showDateWithType:0];
    }
    return self;
}

- (void)updateUser {
    NSLog(@"登陆成功>>>>>>>>%@ >>>>>%@", SN_USER.user_id, [KK_LastUser getObjectValue]);
    _userModel   = [SNEveryDayModelHelp getUserModel];
    _selectModel = [SNEveryDayModelHelp getModelFromDBWithDate:_selectDate];
    _todaymodel  = [SNEveryDayModelHelp getModelFromDBWithToday];
    _yesModel    = [SNEveryDayModelHelp  getModelFromDBWithYes];
}

- (void)SNPublicClassTimer {
    _count += 10;
    if (_count >= 300) {
        if (!KK_BLESend.isSend && !_isCheck && !KK_BLEConnect.isUpdateing) {
            [KK_BLESend updateData];
            NSLog(@"同步运动睡眠心率大数据>>>>>>>>>");
            NSString *log = [NSString stringWithFormat:@"自动同步心率运动睡眠数据"];
            [self writefileWith:log];
            _count = 0;
        }
    }
}

#pragma mark --- 应用切换到前台模式 ---
- (void)BecomeActive:(NSNotification *)Info {
    if ([_lastDateString isEqualToString:SN_Text(@"今天")]) {
        SN_PublicClass.selectDate = [NSDate date];
    }
}

- (void)setSelectDate:(NSDate *)selectDate {
    _selectDate     = selectDate;
    _lastDateString = [self showDateWithType:0];
    _selectModel    = [SNEveryDayModelHelp getModelFromDBWithDate:_selectDate];
}

//******************* 主页面UI显示属性 begin*******************

- (NSString *)showSelectDate {
    if ([[_selectDate dateToDayString] isEqualToString:[[NSDate date]dateToDayString]]) {
        return SN_Text(@"今天");
    }
    
    return [_selectDate dateToDayString];
}

//心率质量判断
- (NSInteger)heartQuality:(NSInteger)heartValue {
    if (heartValue >= 110) {
        return 3;
    } else if (heartValue >= 60 && heartValue < 110) {
        return 2;
    } else {
        return 1;
    }
}

// 血压舒张压判断
- (NSInteger)bpMaxQuality:(NSInteger)bpMaxValue {
    if (bpMaxValue >= 140) {
        return 3;
    } else if (bpMaxValue >= 90 && bpMaxValue < 140) {
        return 2;
    } else {
        return 1;
    }
}

// 血压收缩压判断
- (NSInteger)bpMinQuality:(NSInteger)bpMinValue {
    if (bpMinValue >= 90) {
        return 3;
    } else if (bpMinValue >= 60 && bpMinValue < 90) {
        return 2;
    } else {
        return 1;
    }
}

// 获取某日期所在的周月年 开始的日期 // 周月年 1 周 2 月 3年
- (NSDate *)getMonthBeginAndEndWith:(NSDate *)newDate withType:(NSInteger)type {
    if (newDate == nil) {
        newDate = [NSDate date];
    }
    double     interval   = 0;
    NSDate     *beginDate = nil;
    NSDate     *endDate   = nil;
    NSCalendar *calendar  = [NSCalendar currentCalendar];
    [calendar setFirstWeekday:1];//设定周一为周首日
    BOOL           ok;
    NSCalendarUnit unit;
    if (type == 1) {
        unit = NSWeekCalendarUnit;
    } else if (type == 2) {
        unit = NSMonthCalendarUnit;
    } else if (type == 3) {
        unit = NSYearCalendarUnit;
    }
    
    ok = [calendar rangeOfUnit:unit startDate:&beginDate interval:&interval forDate:newDate];
    //分别修改为 NSDayCalendarUnit NSWeekCalendarUnit NSYearCalendarUnit
    if (ok) {
        endDate = [beginDate dateByAddingTimeInterval:interval-1];
    }
    return beginDate;
}

//返回开始日期 和 结束日期  获取某日期所在的周月年 开始的日期 // 周月年 1 周 2 月 3年
- (NSArray *)getBeginDateStringAndEndWith:(NSDate *)newDate withType:(NSInteger)type {
    if (newDate == nil) {
        newDate = [NSDate date];
    }
    double     interval   = 0;
    NSDate     *beginDate = nil;
    NSDate     *endDate   = nil;
    NSCalendar *calendar  = [NSCalendar currentCalendar];
    [calendar setFirstWeekday:1];//设定周一为周首日
    BOOL           ok;
    NSCalendarUnit unit;
    if (type == 1) {
        unit = NSWeekCalendarUnit;
    } else if (type == 2) {
        unit = NSMonthCalendarUnit;
    } else if (type == 3) {
        unit = NSYearCalendarUnit;
    }
    
    ok = [calendar rangeOfUnit:unit startDate:&beginDate interval:&interval forDate:newDate];
    //分别修改为 NSDayCalendarUnit NSWeekCalendarUnit NSYearCalendarUnit
    if (ok) {
        endDate = [beginDate dateByAddingTimeInterval:interval-1];
    }
    
    NSMutableArray *array = [NSMutableArray array];
    [array addObject:[beginDate dateToDayString]];
    
    NSString *endString = [self endStringWith:endDate];
    [array addObject:endString];
    //    [array addObject:[endDate dateToDayString]];
    return array;
}

- (NSString *)endStringWith:(NSDate *)date {
    NSString  *select  = [date dateToDayString];
    NSInteger nowCount = [NSDate compareDate:[NSDate date] withAnotherDay:date];
    
    if (nowCount == 1) {
        select = [[NSDate date] dateToDayString];
    }
    return select;
}

// 获取选择月份的天数
- (NSInteger)getSelectMonthDays:(NSDate *)date {
    NSCalendar *calendar           = [NSCalendar currentCalendar];
    NSRange    range               = [calendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:date];
    NSUInteger numberOfDaysInMonth = range.length;
    
    return (unsigned long)numberOfDaysInMonth;
}

// 选择日期是选择日期年的第几周
- (NSInteger)getDaysWeekNumberWithSelectDate:(NSDate *)date {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSInteger  week      = [calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitYear forDate:date];
    
    //    NSLog(@"选择日期是选择日期年的第%ld周",week);
    return week;
}

// 选择日期是选择日期年的第几月
- (NSInteger)getDaysMonthNumberWithSelectDate:(NSDate *)date {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSInteger  month     = [calendar ordinalityOfUnit:NSCalendarUnitMonth inUnit:NSCalendarUnitYear forDate:date];
    
    //    NSLog(@"选择日期是选择日期年的第%ld月",month);
    return month;
}

//选择日期是选择日期年的年份
- (NSInteger)getDaysYearNumberWithSelectDate:(NSDate *)date {
    NSCalendar       *calendar   = [NSCalendar currentCalendar];
    unsigned         unitFlags   = NSYearCalendarUnit |NSMonthCalendarUnit |NSDayCalendarUnit;
    NSDateComponents *components = [calendar components:unitFlags fromDate:date];
    
    //    NSLog(@"选择日期的年份是>>>>%d",components.year);
    return components.year;
}

- (UIView *)ViewForCorner:(UIView *)view {
    UIBezierPath *maskPath  = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(view.width/2, view.width/2)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    
    maskLayer.frame = view.bounds;
    maskLayer.path  = maskPath.CGPath;
    view.layer.mask = maskLayer;
    return view;
}

//周 月 年显示日期
- (NSString *)showDateWithType:(SelectDateType)type {
    NSString *dateString = @"";
    if (type == 0) {
        if ([[_selectDate dateToDayString] isEqualToString:[[NSDate date]dateToDayString]]) {
            dateString = SN_Text(@"今天");
        } else {
            dateString = [_selectDate dateToDayString];
        }
    } else {
        double     interval   = 0;
        NSDate     *beginDate = nil;
        NSDate     *endDate   = nil;
        NSCalendar *calendar  = [NSCalendar currentCalendar];
        [calendar setFirstWeekday:1];//设定周一为周首日
        BOOL           ok;
        NSCalendarUnit unit;
        if (type == 1) {
            unit = NSWeekCalendarUnit;
        } else if (type == 2) {
            unit = NSMonthCalendarUnit;
        } else if (type == 3) {
            unit = NSYearCalendarUnit;
        }
        ok = [calendar rangeOfUnit:unit startDate:&beginDate interval:&interval forDate:_selectDate];
        //分别修改为 NSDayCalendarUnit NSWeekCalendarUnit NSYearCalendarUnit
        if (ok) {
            endDate = [beginDate dateByAddingTimeInterval:interval-1];
        }
        if (type == 1) {
            dateString = [NSString stringWithFormat:@"%@-%@", [beginDate dateToSelectDateShow], [endDate dateToSelectDateShow]];
        } else if (type == 2) {
            dateString = [NSString stringWithFormat:@"%@-%@", [beginDate dateToSelectDateShow], [endDate dateToSelectDateShow]];
        } else if (type == 3) {
            dateString = [NSString stringWithFormat:@"%ld/01-%ld/12", (long)[self getDaysYearNumberWithSelectDate:_selectDate], (long)[self getDaysYearNumberWithSelectDate:_selectDate]];
        }
        //        NSLog(@"开始日期>>>>>>>>%@ 结束日期>>>>>%@",[beginDate dateToDayString],[endDate dateToDayString]);
    }
    return dateString;
}

// 设置多段字体 参数1 字号  参数2 改变文字2 参数3 改变文字2
- (NSMutableAttributedString *)label1With:(NSString *)text withFontsize:(CGFloat)fontsize withChangeText1:(NSString *)text1 withChangeText2:(NSString *)text2 {
    NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:text];
    if (!text) {
        return noteStr;
    }
    NSUInteger first1 = [[noteStr string] rangeOfString:text1].location;
    // 需要改变的区间
    NSRange range1 = NSMakeRange(first1, text1.length);
    [noteStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Helvetica-Bold" size:fontsize] range:range1];
    NSUInteger first2 = [[noteStr string] rangeOfString:text2].location;
    // 需要改变的区间
    NSRange range2 = NSMakeRange(first2, text2.length);
    [noteStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Helvetica-Bold" size:fontsize] range:range2];
    return noteStr;
}

//数据模型 SportModel
- (EveryDayModel *)model {
    EveryDayModel *getModel = [SNEveryDayModelHelp getModelFromDBWithToday];
    return getModel;
}

- (EveryDayModel *)todaymodel {
    NSString *dateStr = [[NSDate date] dateToDayString];
    if (!_todaymodel || ![_todaymodel.dateString isEqualToString:dateStr]) {
        _todaymodel = [SNEveryDayModelHelp getModelFromDBWithToday];
    }
    return _todaymodel;
}

- (EveryDayModel *)yesModel {
    NSString *dateStr = [[[NSDate date] dateAfterDay:-1] dateToDayString];
    if (!_yesModel || ![_yesModel.dateString isEqualToString:dateStr]) {
        _yesModel = [SNEveryDayModelHelp getModelFromDBWithYes];
    }
    return _yesModel;
}

- (EveryDayModel *)getEveryDayModelWithDate:(NSDate *)date {
    EveryDayModel *model = [SNEveryDayModelHelp getModelFromDBWithDate:date];
    return model;
}

- (EveryDayModel *)selectModel {
    _selectModel = [SNEveryDayModelHelp getModelFromDBWithDate:_selectDate];
    return _selectModel;
}

- (NSString *)getWithSql:(NSString *)sql {
    return [[EveryDayModel getUsingLKDBHelper]executeScalarWithSQL:sql arguments:nil];
}

- (void)writefileWith:(NSString *)string {
    NSArray  *paths    = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *homePath = [paths objectAtIndex:0];
    NSString *fileName = [NSString stringWithFormat:@"%@_updateDetail.text", [[NSDate date]dateToDayString]];
    //    NSString *fileName = [NSString stringWithFormat:@"sport_step_net.text"];
    NSString      *filePath    = [homePath stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if (![fileManager fileExistsAtPath:filePath]) { //如果不存在
        NSString *str = [NSString stringWithFormat:@"日期:%@", [[NSDate date]dateToDayString]];
        [str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
    [fileHandle seekToEndOfFile];  //将节点跳到文件的末尾
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm:ss"];
    NSString *datestr    = [dateFormatter stringFromDate:[NSDate date]];
    NSString *str        = [NSString stringWithFormat:@"\n%@\n%@\n", datestr, string];
    NSData   *stringData = [str dataUsingEncoding:NSUTF8StringEncoding];
    [fileHandle writeData:stringData]; //追加写入数据
    [fileHandle closeFile];
}

- (void)writefileWithNet:(NSString *)string {
    NSArray  *paths    = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *homePath = [paths objectAtIndex:0];
    NSString *fileName = [NSString stringWithFormat:@"%@_uoloadToServer.text", [[NSDate date]dateToDayString]];
    //    NSString *fileName = [NSString stringWithFormat:@"sport_step_net.text"];
    NSString      *filePath    = [homePath stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if (![fileManager fileExistsAtPath:filePath]) { //如果不存在
        NSString *str = [NSString stringWithFormat:@"日期:%@", [[NSDate date]dateToDayString]];
        [str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
    [fileHandle seekToEndOfFile];  //将节点跳到文件的末尾
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm:ss"];
    NSString *datestr    = [dateFormatter stringFromDate:[NSDate date]];
    NSString *str        = [NSString stringWithFormat:@"\n%@\n%@\n", datestr, string];
    NSData   *stringData = [str dataUsingEncoding:NSUTF8StringEncoding];
    [fileHandle writeData:stringData]; //追加写入数据
    [fileHandle closeFile];
}

#pragma sportModel
// 今日与昨天的运动参数
- (SportModel *)todaySport {
    NSString *dateStr = [[NSDate date] dateToDayString];
    if (!_todaySport || ![_todaySport.dateString isEqualToString:dateStr]) {
        _todaySport = [SportModel getSportModelFromDB];
    }
    return _todaySport;
}

- (SportModel *)yesSport {
    NSString *dateStr = [[[NSDate date] dateAfterDay:-1] dateToDayString];
    if (!_yesSport || ![_yesSport.dateString isEqualToString:dateStr]) {
        _yesSport = [SportModel getSportModelFromDBWithDayString:dateStr];
    }
    return _yesSport;
}

// 今日与昨天的睡眠参数
- (SleepModel *)todaySleep {
    NSString *dateStr = [[NSDate date] dateToDayString];
    
    if (!_todaySleep || ![_todaySleep.dateString isEqualToString:dateStr]) {
        _todaySleep = [SleepModel getSleepModelFromDB];
    }
    return _todaySleep;
}

- (SleepModel *)yesSleep {
    NSString *dateStr = [[[NSDate date] dateAfterDay:-1] dateToDayString];
    
    if (!_yesSleep || ![_yesSleep.dateString isEqualToString:dateStr]) {
        _yesSleep = [SleepModel getSleepModelFromDBWithDayString:dateStr];
    }
    return _yesSleep;
}

// 今日与昨天的心率参数
- (HeartModel *)todayHeart {
    NSString *dateStr = [[NSDate date] dateToDayString];
    if (!_todayHeart || ![_todayHeart.dateString isEqualToString:dateStr]) {
        _todayHeart = [HeartModel getHeartModelFromDB];
    }
    return _todayHeart;
}

- (HeartModel *)yesHeart {
    NSString *dateStr = [[[NSDate date] dateAfterDay:-1] dateToDayString];
    
    if (!_yesHeart || ![_yesHeart.dateString isEqualToString:dateStr]) {
        _yesHeart = [HeartModel getHeartModelFromDBWithDayString:dateStr];
    }
    return _yesHeart;
}

// 今日与昨天的血氧
- (OxModel *)todayOx {
    NSString *dateStr = [[NSDate date] dateToDayString];
    
    if (!_todayOx || ![_todayOx.dateString isEqualToString:dateStr]) {
        _todayOx = [OxModel getOxModelFromDB];
    }
    return _todayOx;
}

- (OxModel *)yesOx {
    NSString *dateStr = [[[NSDate date] dateAfterDay:-1] dateToDayString];
    
    if (!_yesOx || ![_yesOx.dateString isEqualToString:dateStr]) {
        _yesOx = [OxModel getOxModelFromDBWithDayString:dateStr];
    }
    return _yesOx;
}

// 今日与昨天的血压
- (BpModel *)todayBp {
    NSString *dateStr = [[NSDate date] dateToDayString];
    
    if (!_todayBp || ![_todayBp.dateString isEqualToString:dateStr]) {
        _todayBp = [BpModel getBpModelFromDB];
    }
    return _todayBp;
}

- (BpModel *)yesBp {
    NSString *dateStr = [[[NSDate date] dateAfterDay:-1] dateToDayString];
    
    if (!_yesBp || ![_yesBp.dateString isEqualToString:dateStr]) {
        _yesBp = [BpModel getBpModelFromDBWithDayString:dateStr];
    }
    return _yesBp;
}

@end

